package cn.qingfeng.a004_chat_v3.client;

import cn.qingfeng.a004_chat_v3.message.*;
import cn.qingfeng.a004_chat_v3.protocol.MessageCodoc;
import cn.qingfeng.a004_chat_v3.protocol.ProtocolFrameDecoder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

//@Slf4j
public class ChatClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Scanner scanner = new Scanner(System.in);
        AtomicBoolean LOGIN_FLAG = new AtomicBoolean(false);
        AtomicBoolean EXIT_FLAG = new AtomicBoolean(false);
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    sc.pipeline().addLast(new ProtocolFrameDecoder());
                    sc.pipeline().addLast(new MessageCodoc());
                    sc.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));

                    // 用来判断是不是 读空闲时间过长，或 写空闲时间过长
                    // 3s 内如果没有向服务器写数据，会触发一个 IdleState#WRITER_IDLE 事件
                    sc.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                    // ChannelDuplexHandler 可以同时作为入站和出站处理器
                    sc.pipeline().addLast(new ChannelDuplexHandler() {
                        // 用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发了写空闲事件
                            if (event.state() == IdleState.WRITER_IDLE) {
//                                System.out.println("3s 没有写数据了，发送一个心跳包");
//                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                    });

                    sc.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter() {
                        // 接收响应消息
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            System.out.println("msg: " + msg);
                            if (msg instanceof LoginResponseMessage) {
                                LoginResponseMessage response = (LoginResponseMessage) msg;
                                boolean success = response.isSuccess();
                                if (success) {
                                    LOGIN_FLAG.set(true);
                                }
                                // 让计数变为0，然后就能唤醒awit处的进程了
                                WAIT_FOR_LOGIN.countDown();
                            }
                        }

                        // 在连接建立后触发 active 事件
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            System.out.println("连接已建立");
                            new Thread(() -> {
                                System.out.println("请输入用户名:");
                                String username = scanner.nextLine();
                                if (EXIT_FLAG.get()) {
                                    return;
                                }
                                System.out.println("请输入密码:");
                                String password = scanner.nextLine();
                                if (EXIT_FLAG.get()) {
                                    return;
                                }
                                ctx.writeAndFlush(new LoginRequestMessage(username, password));
                                System.out.println("请稍后...");

                                try {
                                    WAIT_FOR_LOGIN.await();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                if (!LOGIN_FLAG.get()) {
                                    System.out.println("登录失败，退出");
                                    ctx.channel().close();
                                    return;
                                }

                                for (; ; ) {
                                    System.out.println("==================================");
                                    System.out.println("send [toUsername] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3...]");
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("==================================");
                                    String line = scanner.nextLine();
                                    if (EXIT_FLAG.get()) {
                                        return;
                                    }
                                    String[] splits = line.split(" ");
                                    String instruction = splits[0];

                                    if ("quit".equals(line)) {
                                        ctx.channel().close();
                                        return;
                                    } else {
                                        if ("send".equals(instruction)) {
                                            ctx.writeAndFlush(new SendRequestMessage(username, splits[1], splits[2]));
                                        } else if ("gsend".equals(instruction)) {
                                            ctx.writeAndFlush(new GsendRequestMessage(username, splits[1], splits[2]));
                                        } else if ("gcreate".equals(instruction)) {
                                            List<String> members = new Gson().fromJson(splits[2], new TypeToken<List<String>>() {
                                            }.getType());
                                            ctx.writeAndFlush(new GcreateRequestMessage(username, splits[1], members));
                                        } else if ("gmembers".equals(instruction)) {
                                            ctx.writeAndFlush(new GmembersRequestMessage(username, splits[1]));
                                        } else if ("gjoin".equals(instruction)) {
                                            ctx.writeAndFlush(new GjoinRequestMessage(username, splits[1]));
                                        } else if ("gquit".equals(instruction)) {
                                            ctx.writeAndFlush(new GquitRequestMessage(username, splits[1]));
                                        }
                                    }
                                }
                            }, "scanner in").start();
                        }

                        // 在连接断开时触发
                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            System.out.println("连接已经断开，按任意键退出..");
                            EXIT_FLAG.set(true);
                        }

                        // 在出现异常时触发
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            System.out.println("连接已经断开，按任意键退出.." + cause.getMessage());
                            EXIT_FLAG.set(true);
                        }
                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();

            channel.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
